//
//  ShakeComponent.cpp
//  cake
//
//  Created by luotianqiang1 on 17/2/28.
//
//

#include "ShakeComponent.h"
IMPLEMENT_COCOS2DX_CLASS(ShakeComponent);

const std::string ShakeComponent::shakeStart = "shakeStart";
const std::string ShakeComponent::shakeStop = "shakeStop";

ShakeComponent::ShakeComponent(){
    _changeInterval = Vec3(0.0f,0.0f,0.0f);
    _preShakeAccel = Vec3::ZERO;
    isFirst = true;
}

bool ShakeComponent::init(){
    if(AccleComponent::init()){
        auto _touchComponent = TouchNodeComponent::create();
        _touchComponent->addListners(ComponentTouchEnd, [=](LQComponent*,OperateListner*){
            _touchComponent->setEnabled(false);
            dispatcherEventWithData(shakeStart, _preShakeAccel);
            this->setEnabled(false);
        });
        _touchComponent->setSwallowTouches(false);
        addComponent(_touchComponent);
        return true;
    }
    return false;
}

void  ShakeComponent::dispatcherAccelEvent(Acceleration * _acceleration, Event * _event){
    if(_enabled&& _owner != nullptr) {
        auto _currentAccel = Vec3(_acceleration->x,_acceleration->y,_acceleration->z);
        if(isFirst){
            isFirst = false;
            _preShakeAccel = _currentAccel;
        }else {
            float distance = _currentAccel.distanceSquared(_preShakeAccel);
            if(distance>0.6){
                log("distance == %f",distance);
                _preShakeAccel = _currentAccel;
                dispatcherEventWithData(shakeStart, _preShakeAccel);
            }else {
                dispatcherEvent(shakeStop);
            }
        }
    }
}